package com.Xht.www.servlet;

//后端响应退房申请的请求

import com.Xht.www.dao.UserHistoryOrdersDAO;
import com.Xht.www.po.UserHistoryOrdersPO;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;

@WebServlet("/checkOut")
public class CheckOutServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/plain;charset=UTF-8");

        try {
            // 获取参数
            String orderIdParam = request.getParameter("orderId");
            String userIdParam = request.getParameter("userId");

            if (orderIdParam == null || userIdParam == null) {
                response.getWriter().write("参数错误，请提供订单ID和用户ID");
                return;
            }

            int orderId = Integer.parseInt(orderIdParam);
            int userId = Integer.parseInt(userIdParam);

            // 获取订单DAO
            UserHistoryOrdersDAO orderDAO = new UserHistoryOrdersDAO();

            // 查询订单
            UserHistoryOrdersPO order = orderDAO.getOrderById(orderId);

            if (order == null) {
                response.getWriter().write("订单不存在");
                return;
            }

            // 验证订单所属用户
            if (order.getUserId() != userId) {
                response.getWriter().write("无权操作此订单");
                return;
            }

            // 验证订单状态（只有"已入住"状态可以退房）
            if (!"已入住".equals(order.getOrderStatus())) {
                response.getWriter().write("订单状态不符合要求，无法办理退房");
                return;
            }

            // 更新订单状态为"已完成"
            order.setOrderStatus("已完成");

            // 设置实际退房时间（如果需要）
            order.setCheckOutTime(new Timestamp(new Date().getTime()));

            // 更新订单
            boolean success = orderDAO.updateOrder(order);

            if (success) {
                response.getWriter().write("退房成功，订单已完成");
            } else {
                response.getWriter().write("退房失败，请重试");
            }

        } catch (NumberFormatException e) {
            response.getWriter().write("参数格式错误");
            e.printStackTrace();
        } catch (Exception e) {
            response.getWriter().write("服务器内部错误，请稍后再试");
            e.printStackTrace();
        }
    }
}
